package com.framework.bdf4j.comm.web;

import java.util.Collection;

import com.framework.bdf4j.comm.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.util.AesUtil;
import com.framework.bdf4j.sysadm.service.impl.MyUserDetailsService;
import com.framework.bdf4j.sysadm.vo.SecurityUser;

import lombok.extern.slf4j.Slf4j;

/**
 * <b>文件名： </b>MyAuthenticationProvider.java<br/>
 * <b>类描述： </b>自定义认证处理器<br/>
 */
@Slf4j
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserDetailsService myUserDetailsService;
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Autowired
    private RedisUtils redisUtils;

    @Value("${login.retryNumber}")
    private String retryNumber;

    /* 
     * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String tenantid = (String)WebUtil.getHttpSession(Constants.TENANT_ID);
        String username = authentication.getName();
        String password = (String)authentication.getCredentials();
        password = AesUtil.decryptStr(password);
        Authentication authen = null;
        SecurityUser user = null;

        redisUtils.checkUser(username);

        try {
            user = (SecurityUser)myUserDetailsService.loadUserByUsername(username);
            if (!ENCODER.matches(password, user.getPassword())) {
                redisUtils.setLoginRedis(username);
                Integer value = redisUtils.getValue(username);
                throw new BadCredentialsException("用户名或者密码错误，您还剩下 " + (Integer.parseInt(retryNumber) - value) + " 次机会");
            }

            if (tenantid != null && !tenantid.equals(user.getTenantId().toString())) {
                // throw new BadCredentialsException("此租户下无此用户");
                redisUtils.setLoginRedis(username);
                Integer value = redisUtils.getValue(username);
                throw new BadCredentialsException("用户名或者密码错误，您还剩下 " + (Integer.parseInt(retryNumber) - value) + " 次机会");
            }

            redisUtils.deleteRedis(username);

            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            authen = new UsernamePasswordAuthenticationToken(user, password, authorities);
            WebUtil.saveHttpCurrentUserId(user.getUserId());
            WebUtil.saveHttpCurrentUserDeptId(user.getDeptId());
            WebUtil.saveHttpCurrentRoles(user.getRoles());
            WebUtil.setHttpSession(Constants.CURRENT_USERNAME, username);
        } catch (AuthenticationException ae) {
            log.error(ae.getMessage(), ae);
            throw ae;
        }
        return authen;
    }

    /* 
     * @see org.springframework.security.authentication.AuthenticationProvider#supports(java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
